﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.Messages;

namespace HJT212_Protocol_DAL.DAO
{
    public class SaveAutoUploadDataDao : BaseDao
    {
        /// <summary>
        /// 处理需要自动保存数据的
        /// </summary>
        //private List<string> AutoSaveDataDicts = new List<string>() { "2011", "2031", "2051", "2061" };
        private List<string> AutoSaveDataDicts = new List<string>() { "2011", "2051", "2031", "2061" };
        /// <summary>
        /// 保存自动上报的数据
        /// </summary>
        /// <param name="Tmsg">上报上来的数据</param>
        public void SaveAutoUpLoadData(TextMessage Tmsg)
        {
            try
            {
                if (Tmsg == null) return;
                string cn = Tmsg.CN;
                string cp = Tmsg.CP;
                if (string.IsNullOrEmpty(cn) || string.IsNullOrEmpty(Tmsg.MN) ||
                    string.IsNullOrEmpty(cp) || !AutoSaveDataDicts.Contains(cn)) return;

                #region 判断数据类型
                string tbName = "";
                string tbName1 = "";
                string Dtype = "0";//实时0、分钟1、小时2、日数据3
                switch (cn)
                {
                    case "2011":
                        tbName = "OriginalityData";//实时数据
                        Dtype = "0";
                        break;
                    case "2051":
                        tbName = "BaseHistoryData1";//分钟数据
                        tbName1 = "BaseHistoryData";
                        Dtype = "1";
                        break;
                    case "2031":
                        tbName = "BaseDayData";//天数据
                        Dtype = "3";
                        break;
                    case "2061":
                        tbName = "BaseHourData";//小时数据
                        Dtype = "2";
                        break;
                }
                #endregion

                #region 指令内容实例
                //                string cp =
                //                    @"ST=32;CN=2011;PW=123456;MN=88888880000001;CP
                //                    =&&DataTime=20040516020111;B01_Rtd=100;011-Rtd 
                //                    =1.1,011-Flag=N;101-Rtd =2.2,101-Flag=N&&";


                //                string cpp =
                //                    @"ST=32;CN=2051;PW=123456;MN=88888880000001;CP
                //                    =&&DataTime=20040516021000;
                //                    B01_Cou=100;
                //                    101_Cou=1.1,101-Min=1.1,101-Avg=1.1,101-Max=1.1;
                //                    011_Cou=1.1,011-Min=2.1,011-Avg=2.1,011-Max=2.1
                //                    &&"; 
                #endregion

                #region 得到时间
                cp = cp.Replace(" ", "").Replace("　", "");//去除空格
                string[] paras = cp.Split(';');
                if (paras.Count() <= 0) return;
                List<string> lstPara = paras.ToList();
                var dtm = lstPara.Where(itm => itm.ToUpper().IndexOf("DATATIME") >= 0);
                string dtime = "";
                DateTime DateTm = DateTime.Now;
                if (dtm != null && dtm.Count() > 0)
                {
                    string dt = dtm.First();
                    string[] dtms = dt.Split('=');
                    if (dtms.Count() > 1)
                    {
                        dtime = dtms[1];
                        lstPara.Remove(dt);
                    }
                }
                if (string.IsNullOrEmpty(dtime)) return;//时间为空，说明不合法
                DateTm = DateTime.ParseExact(dtime, "yyyyMMddHHmmss",
                                             System.Threading.Thread.CurrentThread.CurrentCulture);
                #endregion

                string P_Id = "";

                #region 根据MN检索P_ID
                /*
                P_Id = GetPidByMn(Tmsg.MN);
                if (string.IsNullOrEmpty(P_Id)) return;
                 */
                #endregion

                List<string> lstSqls = new List<string>();

                #region Sql
                string sql = @"INSERT INTO 
                              {0}
                            (
                              P_ID,
                              ParamID,
                              ParamValue,
                              CollectionDateTime,
                              DataState
                            ) 
                            VALUES (
                              '{1}',
                              '{2}',
                              {3},
                              '{4}',
                              '{5}'
                            );";
                //                string sql2 =
                //                    @"EXEC [procInsertHisData]  @Param_ID, @Param_Values, @CDataState,
                //                                @CollPoint, @DType, @CDateTime, @SDateTime ;";
                string sql2 =
                    @"EXEC [procInsertHisData]  '{0}', '{1}', '{2}',
                                 '{3}', {4}, '{5}', '{6}' ;";



                #endregion

                #region 拆数据
                string cpps = cp.Replace(";", ",").TrimEnd(',');
                string[] cppList = cpps.Split(',');
                string dtmStr = "DATATIME";
                string flagStr = "-FLAG=";
                for (int i = 0; i < cppList.Length; i++)
                {
                    string s = cppList[i];
                    if (s.ToUpper().IndexOf(dtmStr) >= 0 || s.ToUpper().IndexOf(flagStr) >= 0) continue;
                    string flag = "";
                    if (i < cppList.Length - 1)
                    {
                        string s1 = cppList[i + 1];
                        if (!string.IsNullOrEmpty(s1) && s1.ToUpper().IndexOf(flagStr) >= 0)
                        {
                            flag = s1.Split('=')[1];
                        }
                    }
                    string[] p0s = s.Split('=');
                    lstSqls.Add(string.Format(sql2, p0s[0], p0s[1], flag, Tmsg.MN, Dtype, DateTm, DateTime.Now));
                }
                #endregion


                if (lstSqls.Count > 0)
                {
                    //helper.ExecuteNonQueryTransaction(lstSqls);
                    lstSqls.ForEach(itm =>
                    {
                        try
                        {
                            helper.ExecuteNonQuery(itm);
                        }
                        catch (Exception ex)
                        {
                            log.Error("出现异常", ex);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
        }


        public void dd()
        {
            TextMessage tmg = new TextMessage();
            tmg.MN = "88888880000015";
            tmg.CN = "2011";
            tmg.CP =
                "DataTime=20120814093350;102-Rtd=1.92,102-Flag=N;103-Rtd=26.8,103-Flag=N;106-Rtd=13.79,106-Flag=N;107-Rtd=2.39,107-Flag=N;108-Rtd=7.41,108-Flag=N;109-Rtd=1577.18,109-Flag=N;116-RS=1727.91,116-Flag=N;117-RS=680.45,117-Flag=N;130-Rtd=16.06,130-Flag=N;131-Rtd=0.47,131-Flag=N;132-RS=34,132-Flag=N;133-Rtd=51,133-Flag=N;137-Rtd=0.6,137-Flag=N;139-Rtd=370.89,139-Flag=N;140-Rtd=0.82,140-Flag=N;141-Rtd=520.57,141-Flag=N;142-Rtd=21.18,142-Flag=N;A12-Rtd=28.09,A12-Flag=N;A13-Rtd=58.95,A13-Flag=N;A14-Rtd=233.66,A14-Flag=N;A15-Rtd=2.3,A15-Flag=N;A16-Rtd=990.63,A16-Flag=N;A18-Rtd=28.7,A18-Flag=N;A19-Rtd=54,A19-Flag=N;";

            SaveAutoUpLoadData(tmg);
        }

        /// <summary>
        /// 根据MN检索Pid
        /// </summary>
        /// <param name="Mn">MN</param>
        /// <returns>P_id</returns>
        public string GetPidByMn(string Mn)
        {
            try
            {
                if (string.IsNullOrEmpty(Mn)) return null;
                string sql = "select top 1 P_ID from PointsOnlineState where MN='{0}' ";
                string pid = string.Format("{0}", helper.ExecuteScalar(string.Format(sql, Mn)));
                return pid;
            }
            catch (Exception ex)
            {
                log.Error("出现异常", ex);
            }
            return null;
        }

    }
}
